/**
 * @Title:  ArtRecordEdit.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-5-12 上午10:57:44 
 * @version:  V1.0 
 */

package artid.com.arttogoa.keeponrecord;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import artid.com.arttogoa.HomeActivity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.fragment.CompleteGraphFragment;
import artid.com.arttogoa.fragment.EditCache;
import artid.com.arttogoa.fragment.GroupPhotoFragment;
import artid.com.arttogoa.fragment.MicFragment;
import artid.com.arttogoa.parser.ArtworkImageUpload;
import artid.com.arttogoa.parser.FilesBean;
import artid.com.arttogoa.parser.MicMapBean;
import artid.com.arttogoa.parser.RecordDetailList;
import artid.com.arttogoa.parser.UserItem;
import artid.com.arttogoa.task.CallbackSky;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;

/**
 * TODO<备案编辑页>
 * 
 * @author 熊彬
 * @data: 2016-5-12 上午10:57:44
 * @version: V1.0
 */
public class ArtRecordEdit extends FragmentActivity implements OnClickListener,
		CallbackSky {
	private View v;
	private List<ImageView> imList = new ArrayList<ImageView>();
	private List<TextView> tvList = new ArrayList<TextView>();
	private int[] sel = { R.drawable.shuzi_1_sel, R.drawable.shuzi_2_sel,
			R.drawable.shuzi_3_sel }; 
	private int[] nor = { R.drawable.shuzi_1_nor, R.drawable.shuzi_2_nor,
			R.drawable.shuzi_3_nor };
	private ImageView v1, v2, v3;
	private TextView t1, t2, t3, editButton;
	private Fragment mContent;// 当前页面
	/**
	 * 用于对Fragment进行管理
	 */
	private FragmentManager fragmentManager;
	private FragmentTransaction begin;

	public static String curFragmentTag;

	private GroupPhotoFragment mGroupPhotoFragment;
	private CompleteGraphFragment mCompleteGraphFragment;
	private MicFragment mMicFragment;
	private static RequestQueue mSingleQueue;
	private RecordDetailList item;
	private String[] images = { null, null, null };
	ArrayList<MicMapBean> micMapList;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_artrecord_edit);
		ArtWorkApp.getInstance().addArtActivity(ArtRecordEdit.this);
		v = (View) findViewById(R.id.view_line);
		/**
		 * 编辑上部切换按钮
		 */
		v1 = (ImageView) findViewById(R.id.iv_com);
		v2 = (ImageView) findViewById(R.id.iv_heying);
		v3 = (ImageView) findViewById(R.id.iv_mic);
		t1 = (TextView) findViewById(R.id.tv_1);
		t2 = (TextView) findViewById(R.id.tv_2);
		t3 = (TextView) findViewById(R.id.tv_3);

		editButton = (TextView) findViewById(R.id.title_right);// 提交按钮
		editButton.setText("提交审核");
		editButton.setVisibility(View.VISIBLE);
		editButton.setOnClickListener(this);
		mSingleQueue = Volley.newRequestQueue(this);
		imList.add(v1);
		imList.add(v2);
		imList.add(v3);
		tvList.add(t1);
		tvList.add(t2);
		tvList.add(t3);
		v1.setOnClickListener(this);
		v2.setOnClickListener(this);
		v3.setOnClickListener(this);
		/**
		 * 初始化连接线的长度
		 */

		int width = Integer.valueOf(NetUtils.getDisplayMetrics(
				ArtRecordEdit.this).get(NetUtils.DM_WIDTH));
		setMargins(v, width / 3 / 2, 0, width / 3 / 2, 0);
		item = (RecordDetailList) DataKeeper.readSerializable(
				ArtRecordEdit.this, RecordDetailList.class);
		System.out.println(item.toString());
		selectOption(0);
		initFragmentManger();
		artwork = new ArtworkImageUpload();
	}

	/**
	 * 
	 * @Description: 初始化FragmentManger
	 * @Title: initFragmentManger
	 * @param:
	 * @return: void
	 * @author: JianBo Yang
	 */
	private void initFragmentManger() {
		mGroupPhotoFragment = new GroupPhotoFragment(this);
		mContent = mGroupPhotoFragment;
		fragmentManager = getSupportFragmentManager();
		begin = fragmentManager.beginTransaction();
		begin.add(android.R.id.tabcontent, mContent);
		begin.commit();
	}
	
	public void switchContent(Fragment from, Fragment to) {
		if (from != to) {
			mContent = to;
			FragmentTransaction transaction = fragmentManager
					.beginTransaction();
			// 先判断是否被add过
			if (!to.isAdded()) {
				// 隐藏当前的fragment，add下一个到Activity中
				transaction.hide(from).add(android.R.id.tabcontent, to)
						.commit();
			} else {
				// 隐藏当前的fragment，显示下一个
				transaction.hide(from).show(to).commit();
			}
		}
	}

	/**
	 * 初始化选项按钮默认选中
	 * 
	 * @param index
	 */
	private void selectOption(int index) {
		// TODO Auto-generated method stub
		for (int i = 0; i < imList.size(); i++) {
			if (index == i) {
				imList.get(i).setImageResource(sel[i]);
				tvList.get(i).setTextColor(
						this.getResources().getColor(R.color.yuan_sel));
			} else {
				imList.get(i).setImageResource(nor[i]);
				tvList.get(i).setTextColor(
						this.getResources().getColor(R.color.yuan_nor));
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_com:
			selectOption(0);
			switchContent(mContent, mGroupPhotoFragment);
			break;
		case R.id.iv_heying:
			selectOption(1);
			if (mCompleteGraphFragment == null) {
				mCompleteGraphFragment = new CompleteGraphFragment(this);
			}
			switchContent(mContent, mCompleteGraphFragment);
			break;
		case R.id.iv_mic:
			selectOption(2);
			if (mMicFragment == null) {
				mMicFragment = new MicFragment(this);
			}
			switchContent(mContent, mMicFragment);
			break;
		case R.id.title_right:
			if (mMicFragment != null) {
				micMapList = mMicFragment.getMapList();
				if (micMapList == null)
					return;
			} else {
				AlertUtils.initSubmitSumAlertDialog(ArtRecordEdit.this,
						"您没有进行编辑，请编辑后再提交");
				return;
			}
			if (mGroupPhotoFragment != null) {
				artwork = mGroupPhotoFragment.getData();
			} else {
				AlertUtils.initSubmitSumAlertDialog(ArtRecordEdit.this,
						"您没有进行编辑，请编辑后再提交");
				return;
			}
			if (mCompleteGraphFragment != null) {
				artwork1 = mCompleteGraphFragment.getData();
			} else {
				AlertUtils.initSubmitSumAlertDialog(ArtRecordEdit.this,
						"您没有进行编辑，请编辑后再提交");
				return;
			}
			if (artwork1 == null || artwork == null) {

				return;
			}

			FileInputStream fis;
			try {
				imageIengh = 0;
				for (int i = 0; i < images.length; i++) {
					if (!TextUtils.isEmpty(images[i])) {
						fis = new FileInputStream(images[i]);
						imageIengh = imageIengh + fis.available();
					}
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (!EditCache.gChenge && !EditCache.cChenge && !EditCache.mChenge) {
				AlertUtils.initSubmitSumAlertDialog(ArtRecordEdit.this,
						"您没有进行编辑，请编辑后再提交");
				return;
			}
			if (EditCache.gChenge || EditCache.cChenge) {
				AlertUtils.initUploadAlertDialog2(ArtRecordEdit.this,
						ArtRecordEdit.this.getWindowManager()
								.getDefaultDisplay().getWidth(), "正在上传合影及完整图");
				new Thread(networkTask).start();
			} else {
				AlertUtils.initUploadAlertDialog2(ArtRecordEdit.this,
						ArtRecordEdit.this.getWindowManager()
								.getDefaultDisplay().getWidth(),
						"正在提交第1个微观图及描述信息");
				new Thread(micNetworkTask).start();
			}

			break;
		default:
			break;
		}
	}

	private AlertDialog alertDialog;

	/**
	 * 展示修改提示，如果确定修改主图，则标点图描述信息等全部清除
	 */
	private void showEditInfo() {
		alertDialog = AlertUtils.initEditAlertDialog(ArtRecordEdit.this,
				ArtRecordEdit.this.getWindowManager().getDefaultDisplay()
						.getWidth(), new OnClickListener() {
					@Override
					public void onClick(View view) {
						// TODO Auto-generated method stub
						switch (view.getId()) {
						case R.id.tv_ok:
							alertDialog.dismiss();
							showPhotoInfo();
							break;
						default:
							break;
						}
					}
				});
	}

	/**
	 * 展示图片选择菜单 b
	 */
	private void showPhotoInfo() {
		alertDialog = AlertUtils.initPhotoAlertDialog(ArtRecordEdit.this,
				ArtRecordEdit.this.getWindowManager().getDefaultDisplay()
						.getWidth(), new OnClickListener() {
					@Override
					public void onClick(View view) {
						// TODO Auto-generated method stub
						switch (view.getId()) {
						case R.id.tv_phone:
							Intent intentMe = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(intentMe, 1);
							alertDialog.dismiss();
							break;
						case R.id.tv_choice:
							Intent intent = new Intent(ArtRecordEdit.this,
									HomeActivity.class);
							startActivityForResult(intent, 2);
							alertDialog.dismiss();

							break;
						default:
							break;
						}
					}
				});
	}

	private int Type;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.example.artworkarta.task.CallbackSky#callBack(int)
	 */
	@Override
	public void callBack(int index) {
		// TODO Auto-generated method stub
		Type = index;
		switch (index) {
		case 1:// 合影
			showPhotoInfo();
			break;
		case 2:// 完整图
			showEditInfo();
			break;
		case 3:// 落款
			showPhotoInfo();
			break;

		default:
			break;
		}

	}

	/**
	 * 所有fragment内进行的点击操作，跳转其他页面进行的回调，都经由本页面处理 （三个图片的编辑，跳转微观图浏览、微观图编辑页面回调）
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		String imageUrl = null;
		if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
				Log.i("TestFile",
						"SD card is not avaiable/writeable right now.");
				return;
			}
			@SuppressWarnings("static-access")
			String name = new DateFormat().format("yyyyMMdd_hhmmss",
					Calendar.getInstance(Locale.CHINA))
					+ ".jpg";
			// Toast.makeText(this, name, Toast.LENGTH_LONG).show();
			Bundle bundle = data.getExtras();
			Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式

			FileOutputStream b = null;
			// ???????????????????????????????为什么不能直接保存在系统相册位置呢？？？？？？？？？？？？`
			File file = new File("/sdcard/myImage/");
			file.mkdirs();// 创建文件夹
			String fileName = "/sdcard/myImage/" + name;
			imageUrl = fileName;
			try {
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else if (requestCode == 2 && resultCode == 3) {
			Bundle bundle = data.getExtras();
			FilesBean fb = (FilesBean) bundle.getSerializable("image");
			imageUrl = fb.getImgURL();
		} else if (requestCode == 2 && resultCode == 4) {
			Bundle bundle = data.getExtras();
			FilesBean fb = (FilesBean) bundle.getSerializable("image");
			System.out.println(fb.getThumbURL());
			imageUrl = fb.getThumbURL();
		} else if (resultCode == 9) {
			MicMapBean mic = (MicMapBean) data.getExtras().getSerializable(
					"data");
			mMicFragment.initMapInfo(mic);

		} else if (resultCode == 10) {
			// NewActivity的返回数据
			@SuppressWarnings("unchecked")
			ArrayList<MicMapBean> micMapList = (ArrayList<MicMapBean>) data
					.getExtras().getSerializable("data");
			mMicFragment.initBrowse(micMapList);

		} else {
			if (mMicFragment != null) {
				mMicFragment.initDelete();
			}
		}
		if (!TextUtils.isEmpty(imageUrl))
			switch (Type) {
			case 1:
				images[0] = imageUrl;
				EditCache.gChenge = true;
				mGroupPhotoFragment.setPhotoImage(imageUrl);
				break;
			case 2:
				images[1] = imageUrl;
				EditCache.cChenge = true;
				mCompleteGraphFragment.setCompleteImage(imageUrl, true);
				if (mMicFragment != null) {
					mMicFragment = null;
				}
				break;
			case 3:
				images[2] = imageUrl;
				EditCache.cChenge = true;
				mCompleteGraphFragment.setInscribeImage(imageUrl);
				break;

			default:
				break;
			}
	}

	private String getUrl(String url) {
		// TODO Auto-generated method stub
		if (url.contains("http")) {
			return url.substring(url.indexOf("/", 10), url.length());
		}
		return url;
	}

	/**
	 * 设置控件的边距
	 * 
	 * @param v
	 * @param l
	 * @param t
	 * @param r
	 * @param b
	 */
	public void setMargins(View v, int l, int t, int r, int b) {
		if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
			ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v
					.getLayoutParams();
			p.setMargins(l, t, r, b);
			v.requestLayout();
		}
	}

	private ArtworkImageUpload artwork;
	private ArtworkImageUpload artwork1;
	private final int TYPE_COM = 1;
	private final int TYPE_MIC = 2;
	private final int TYPE_WANCHENG = 3;
	private long imageIengh;
	/**
	 * 上传合影完整图
	 */
	Runnable networkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			String uri = Cache.upload;
			Map<String, String> params = new HashMap<String, String>();
			params.put("token", AppUtil.getUser().getToken());
			params.put("artid", item.getId());
			params.put("art_type", artwork1.getArt_type());
			params.put("is_file", "2");

			params.put("title", artwork1.getTitle());
			params.put("realname", artwork1.getRealname());
			params.put("width", artwork1.getWidth());
			params.put("height", artwork1.getHeight());
			params.put("age", artwork1.getAge());
			params.put("detail", artwork1.getDetail());
			params.put("gphoto_detail", artwork.getGphoto_detail());
			Map<String, File> files = new HashMap<String, File>();
			if (!TextUtils.isEmpty(images[0]))
				files.put("gphotodata", new File(images[0]));
			if (!TextUtils.isEmpty(images[1]))
				files.put("imgdata", new File(images[1]));
			if (!TextUtils.isEmpty(images[2]))
				files.put("inscribeimg", new File(images[2]));
			System.out.println(params.toString());
			System.out.println(files.size());
			try {
				String Response = post(uri, params, files, TYPE_COM, -1);
				if (TextUtils.isEmpty(Response)) {
					Message m = new Message();
					m.what = -1;
					handler.sendMessage(m);
					return;
				}
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putString("value", Response);
				data.putInt("type", TYPE_COM);
				msg.setData(data);
				msg.what = 1;
				handler.sendMessage(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};
	/**
	 * 上传微观图
	 */
	Runnable micNetworkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			for (int i = 0; i < micMapList.size(); i++) {
				MicMapBean mb = micMapList.get(i);
				Map<String, File> files = new HashMap<String, File>();
				Map<String, String> params = new HashMap<String, String>();
				if (mb.getImage().contains("http")) {
					params.put("60url", mb.getImage());
				} else {
					files.put("microgramdata", new File(mb.getImage()));
				}
				if (mb.getImage200().contains("http")) {
					files.put("microgramdata", new File(mb.getImage200()));
				} else {
					files.put("microgramdatamax", new File(mb.getImage200()));
				}
				params.put("token", AppUtil.getUser().getToken());
				params.put("art_id", item.getId());
				params.put("is_file", "2");
				params.put("is_update", "1");
				params.put("imgtype", mb.getImgtype());
				params.put("number", (i + 1) + "");
				params.put("microgram_detail", mb.getInfo());
				params.put("xcoordinate", mb.getPf().getPointX() + "");
				params.put("ycoordinate", mb.getPf().getPointY() + "");

				String uri = Cache.uploadMicrogram;
				try {
					String Response = post(uri, params, files, TYPE_MIC, i);
					if (TextUtils.isEmpty(Response)) {
						Message m = new Message();
						m.what = -1;
						handler.sendMessage(m);
						break;
					}
					Message msg = new Message();
					Bundle data = new Bundle();
					data.putString("value", Response);
					data.putInt("type", TYPE_MIC);
					data.putInt("index", i);
					msg.setData(data);
					msg.what = 1;
					handler.sendMessage(msg);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}
	};

	/**
	 * 完成
	 */
	Runnable comNetworkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			String uri = Cache.saveartRecord;
			Map<String, String> params = new HashMap<String, String>();
			params.put("token", AppUtil.getUser().getToken());
			params.put("art_id", item.getId());
			try {
				String Response = post(uri, params, null, TYPE_WANCHENG, -1);
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putString("value", Response);
				data.putInt("type", TYPE_WANCHENG);
				msg.setData(data);
				msg.what = 3;
				handler.sendMessage(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};

	public String post(String url, Map<String, String> params,
			Map<String, File> files, int type, int index) throws IOException {
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";
		URL uri = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(120 * 1000); // 缓存的最长时间
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Accept",
				"application/json, text/javascript, */*");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);
		conn.setChunkedStreamingMode(1024);
		// 首先组拼文本类型的参数
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			// sb.append("Content-Type: text/plain; charset=" + CHARSET +
			// LINEND);
			// sb.append("Content-Transfer-Encoding: utf-8" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}
		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());

		outStream.write(sb.toString().getBytes());
		// 发送文件数据
		int length = 0;
		if (files != null)
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\""
						+ file.getKey() + "\"; filename=\""
						+ file.getValue().getName() + "\"" + LINEND);
				// sb1.append("Content-Type: application/octet-stream; charset="
				// + CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());

				InputStream is = new FileInputStream(file.getValue());
				long total = is.available();
				System.out.println("图片的data大小==============" + total);
				byte[] buffer = new byte[1024];
				int len = 0;

				while ((len = is.read(buffer)) != -1) {

					outStream.write(buffer, 0, len);
//					length += len;
//					if (type == TYPE_COM) {
//						Message msg = new Message();
//						msg.what = 2;
//						msg.obj = (int) ((length / (float) imageIengh) * 100);
//						handler.sendMessage(msg);
//					} else if (type == TYPE_MIC) {
//						Message msg = new Message();
//						msg.what = 2;
//						msg.obj = (int) ((length / (float) total) * 100);
//						handler.sendMessage(msg);
//					}
				}
				is.close();
				outStream.write(LINEND.getBytes());

			}
		System.out.println(outStream.toString());
		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();
		// 得到响应码
		StringBuilder sb2 = null;
		try {
			int res = conn.getResponseCode();
			InputStream in = conn.getInputStream();
			sb2 = new StringBuilder();
			if (res == 200) {
				int ch;
				while ((ch = in.read()) != -1) {
					sb2.append((char) ch);
				}
			}
		} catch (SocketTimeoutException e) {
			// TODO: handle exception
			e.printStackTrace();

			return "";
		}

		outStream.close();
		conn.disconnect();
		return sb2.toString();
	}

	/**
	 * 确认提交申请备案
	 */
	private void comNetwork() {

		// TODO Auto-generated method stub
		String uri = Cache.saveartRecord;
		// System.out.println("params=" + params.toString());

		VolleyBasic.getInstance(ArtRecordEdit.this).post(false, false, uri,
				VolleyMap.getInstance().saveartRecord(item.getId()),
				UserItem.class, new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						AlertUtils.dismiss();
						// TODO
						// Auto-generated
						// method stub
						Log.i("my上传3", "请求结果3为-->" + vd.getJson());
						try {
							JSONObject jo = new JSONObject(vd.getJson());
							if (jo.optString("ret").equals("1")) {
								// String
								// state
								// =
								// jo.optJSONObject("data").optString(
								// "state");

								MySharedPreferences.getMySharedPreferences(
										ArtRecordEdit.this).setValue(
										Cache.artIsLoad, "yes");
								Toast.makeText(ArtRecordEdit.this, "上传成功！", 2)
										.show();
								ArtWorkApp.getInstance().artExit();
							} else {
								Toast.makeText(ArtRecordEdit.this,
										jo.optString("msg") + " ", 2).show();
							}

						} catch (JSONException e) {
							// TODO
							// Auto-generated
							// catch
							// block
							e.printStackTrace();
						}
					}

					public void onError(VolleyError volleyError) {
						AlertUtils.dismiss();
					}
				});
	}

	private String state;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				Bundle data = msg.getData();
				String val = data.getString("value");
				int type = data.getInt("type");
				if (!TextUtils.isEmpty(val)) {
					val = val.substring(val.indexOf("{"),
							val.lastIndexOf("}") + 1);
					val = NetUtils.decodeUnicode(val);
					Log.i("mylog", "请求结果为-->" + val);
					try {
						JSONObject jo = new JSONObject(val);
						if (jo.optString("ret").equals("1")) {
							state = jo.optJSONObject("data").optString(
									"state");
							if (type == TYPE_COM) {
								Log.e("com", "完整图落款合影图上传成功");
								if (EditCache.mChenge) {
									AlertUtils.setText("正在提交第1个微观图及描述信息");
									new Thread(micNetworkTask).start();
								} else {
									new Thread(comNetworkTask).start();
								}
							} else if (type == TYPE_MIC) {
								int index = data.getInt("index");
								// Log.e("mic" + oi, "图片" + oi + "上传成功");
								if (state.equals("1")) {
									if (index == micMapList.size() - 1) {
										MySharedPreferences
												.getMySharedPreferences(
														ArtRecordEdit.this)
												.setValue(Cache.artIsLoad,
														"yes");
										MySharedPreferences
												.getMySharedPreferences(
														ArtRecordEdit.this)
												.setValue(Cache.ART_ID,
														item.getId());
										// MySharedPreferences
										// .getMySharedPreferences(context)
										// .setValue(Cache.ARTREC_STATUS,
										// "yes");
										System.out.println("开始请求接口3");
										new Thread(comNetworkTask).start();
										// login();
										// comNetwork();
										// comNetwork();
										// MultiPart(uri, null, params,
										// mMicListenerString,
										// mErrorListener, null);
									} else {
										AlertUtils.setText("正在提交第"
												+ (index + 2) + "个微观图及描述信息");
									}
								} else {
									System.out.println("state=" + state);
								}
							}
							// Intent intent = new Intent(
							// UploadCompleteGraphActivity.this,
							// MicroscopicMapSelectActivity.class);
							// Bundle b = new Bundle();
							// b.putString("state", state);
							// b.putString("art_id", art_id);
							// b.putString("imgUrl",
							// "/storage/emulated/0/zapya/photo/20150127_1033/IMG20141115140855.jpg");
							// intent.putExtras(b);
							// startActivity(intent);
						} else {
							Toast.makeText(ArtRecordEdit.this,
									jo.optString("msg") + " ", 2).show();
							AlertUtils.dismiss();
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					Toast.makeText(ArtRecordEdit.this, "无响应！", 2).show();
				}
				break;
			case 2:
				int i = (Integer) msg.obj;
				AlertUtils.setProgressBar(i);
				break;
			case -2:
				MySharedPreferences.getMySharedPreferences(ArtRecordEdit.this)
						.setValue(Cache.artIsLoad, "yes");
				AlertUtils.dismiss();
				// Toast.makeText(MicroscopicMapSelectActivity.this,
				// "上传成功！", 2).show();
				ArtWorkApp.getInstance().artExit();
				break;
			case -1:
				ToastUtil.toast(ArtRecordEdit.this, "连接超时，请重新请求");
				AlertUtils.dismiss();
				break;
			case 3:
				Bundle bd = msg.getData();
				String req = bd.getString("value");
//				AlertUtils.dismiss();
				if (!TextUtils.isEmpty(req)) {
					Log.i("mylog1", "请求结果为12-->" + req);
					req = req.substring(req.indexOf("{"),
							req.lastIndexOf("}") + 1);
					req = NetUtils.decodeUnicode(req);
					Log.i("mylog2", "请求结果为13-->" + req);
					JSONObject jo;
					try {
						JSONObject json = new JSONObject(req);
						if (json.optString("ret").equals("1")) {
							// String state =
							// jo.optJSONObject("data").optString(
							// "state");
							AlertUtils.setUploadImage(true);

							// Map<String, String> params = new
							// HashMap<String, String>();
							// params.put("token", AppUtil.getUser()
							// .getToken());
							// params.put("art_id", art_id);
							Handler handler1 = new Handler();
							handler1.postDelayed(new Runnable() {
								@Override
								public void run() {
									Message msg = new Message();
									msg.what = -2;
									handler.sendMessage(msg);
								}
							}, 2000);

						} else {
							Toast.makeText(ArtRecordEdit.this,
									json.optString("msg") + " ", 2).show();
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					Toast.makeText(ArtRecordEdit.this, "无响应！", 2).show();
					AlertUtils.dismiss();
				}
				break;

			default:
				break;
			}

			// TODO
			// UI界面的更新等相关操作
		}
	};
}
